package com.bu.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.springframework.stereotype.Service;

import com.bu.model.Topic;

/**
 * @author xueqiang.mi
 * @since 2011-2-21
 */
@Service
public class TopicService {

	public Topic getOrCreate(String name) {
		Topic t = null;
		PersistenceManager pm = PMF.get();
		try {
			t = pm.getObjectById(Topic.class, name);
			return t;
		} catch (Exception e) {
			t = new Topic();
			t.setName(name);
			t.setCrtDate(new Date());
			pm.makePersistent(t);
			return t;
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Topic> list() {
		PersistenceManager pm = PMF.get();
		try {
			Query q = pm.newQuery(Topic.class);
			Collection<Topic> c = pm.detachCopyAll((Collection<Topic>) q.execute());
			return new ArrayList<Topic>(c);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Topic> tree() {
		PersistenceManager pm = PMF.get();
		try {
			Query q = pm.newQuery(Topic.class);
			q.setFilter("level == 0");
			Collection<Topic> c = pm.detachCopyAll((Collection<Topic>) q.execute());
			return new ArrayList<Topic>(c);
		} finally {
			pm.close();
		}
	}
}
